/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.td.auth.googleplus;

import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.app.reportproblem.LoginActivity;
import com.app.reportproblem.MainActivity;
import com.app.reportproblem.R;
import com.app.reportproblem.Utils.PreferenceHelper;
import com.app.reportproblem.httpclient.HttpClientHelper;
import com.app.reportproblem.httpclient.MyJsonHttpResponseHandler;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.android.gms.common.GooglePlayServicesUtil;

/**
 * The TokenInfoActivity is a simple app that allows users to acquire, inspect and invalidate
 * authentication tokens for a different accounts and scopes.
 *
 * In addition see implementations of {@link AbstractGetTokenTask} for an illustration of how to use
 * the {@link GoogleAuthUtil}.
 */
public class SignInGoogleActivity extends Activity {
    private static final String TAG = "SignInGoogleActivity";
    private static final String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email";

    static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
    static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1001;
    static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1002;

    private String mEmail=null;
    PreferenceHelper preferenceHelper;
    ProgressDialog progressDialog;


    public static String TYPE_KEY = "type_key";
    public static enum Type {FOREGROUND, BACKGROUND, BACKGROUND_WITH_SYNC}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        	getWindow().setBackgroundDrawable(new ColorDrawable(0));
        }
        preferenceHelper = new PreferenceHelper(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
            if (resultCode == RESULT_OK) {
                mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                signInAndGetToken();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "You must pick an account", Toast.LENGTH_SHORT).show();
            }
        } else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
                requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
                && resultCode == RESULT_OK) {
            handleAuthorizeResult(resultCode, data);
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void handleAuthorizeResult(int resultCode, Intent data) {
        if (data == null) {
            onResult("Unknown error, click the button again");
            return;
        }
        if (resultCode == RESULT_OK) {
            Log.i(TAG, "Retrying");
            getTask(this, mEmail, SCOPE).execute();
            return;
        }
        if (resultCode == RESULT_CANCELED) {
            onResult("User rejected authorization.");
            return;
        }
        onResult("Unknown error, click the button again");
    }
    
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	Handler handler = new Handler();
    	handler.post(new Runnable() {
			
			@Override
			public void run() {
				signInAndGetToken();
			}
		});
    }

    private void signInAndGetToken() {
        if (mEmail == null) {
            pickUserAccount();
        } else {
            if (isDeviceOnline()) {
                getTask(SignInGoogleActivity.this, mEmail, SCOPE).execute();
            } else {
                Toast.makeText(this, "No network connection available", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /** Starts an activity in Google Play Services so the user can pick an account */
    private void pickUserAccount() {
        String[] accountTypes = new String[]{"com.google"};
        Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, null, null, null, null);
        startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
    }

    /** Checks whether the device currently has a network connection */
    private boolean isDeviceOnline() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }

	public void onResult(final String token) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				try {
					if (token != null && !token.equals("")) {
						Log.e("Tuan", token);
						preferenceHelper.setAccessToken(token);
						/*Toast.makeText(SignInGoogleActivity.this,
								"Login success with token:  " + token,
								Toast.LENGTH_LONG).show();
*/
//						finish();
						loginHttpGoogle();
						return;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				Toast.makeText(SignInGoogleActivity.this, "Login unsuccess",
						Toast.LENGTH_SHORT).show();
				finish();
			}
		});
	}


    public void handleException(final Exception e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (e instanceof GooglePlayServicesAvailabilityException) {
                    // The Google Play services APK is old, disabled, or not present.
                    // Show a dialog created by Google Play services that allows
                    // the user to update the APK
                    int statusCode = ((GooglePlayServicesAvailabilityException)e).getConnectionStatusCode();
                    Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
                            SignInGoogleActivity.this, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
                    dialog.show();
                } else if (e instanceof UserRecoverableAuthException) {
                    // Unable to authenticate, such as when the user has not yet granted
                    // the app access to the account, but the user can fix this.
                    // Forward the user to an activity in Google Play services.
                    Intent intent = ((UserRecoverableAuthException)e).getIntent();
                    startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
                }
            }
        });
    }

    private AbstractGetTokenTask getTask(SignInGoogleActivity activity, String email, String scope) {
    	return new AbstractGetTokenTask(activity, email, scope);
    }
    
    void loginHttpGoogle() {
    	progressDialog = ProgressDialog.show(SignInGoogleActivity.this, "", getString(R.string.logging));
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					progressDialog.dismiss();
					switch (status) {
					case 200:
						JSONObject data = re.getJSONObject("data");
						preferenceHelper.setUserId(data.getInt("userId"));
						preferenceHelper.setName(data.getString("name"));
						preferenceHelper.setMobile(data.getString("mobile"));
//						preferenceHelper.setEmail(edtEmail.getText().toString());
//						preferenceHelper.setPass(edtPass.getText().toString());
						preferenceHelper.setFixed(data.getInt("allowFix"));
						Log.i("DATA", "Dang nhap thanh cong");
						gotoMain();
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		
		httpClientHelper.loginSocial(preferenceHelper.getAccessToken(), "google");
		
	}
    
    void gotoMain() {
		finish();
		Intent t = new Intent(SignInGoogleActivity.this, MainActivity.class);
		t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(t);
	}
    
    
}